package com.math.aistudykbr.utils;

import com.baidu.aip.ocr.AipOcr;
import com.math.aistudykbr.config.BaiduOCRProperties;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

@Slf4j
@RequiredArgsConstructor
@Component
public class BaiduOcrUtil {
    private final BaiduOCRProperties baiduOCRProperties;
    private AipOcr aipOcr;

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        this.aipOcr = new AipOcr(baiduOCRProperties.getAppId(), baiduOCRProperties.getApiKey(), baiduOCRProperties.getSecretKey());
    }

    /**
     * 通用文字识别
     */
    public ArrayList<String> basicGeneral(String path) {
        HashMap<String, String> options = new HashMap<>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

        JSONObject jsonObject = aipOcr.basicGeneral(path, options);
        JSONArray jsonArray = jsonObject.getJSONArray("words_result");

        ArrayList<String> result = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            result.add(jsonArray.getJSONObject(i).getString("words"));
        }
        return result;
    }

    /**
     * 判断是否是图片
     */
    public boolean isImage(InputStream inputStream) {
        if (inputStream == null) {
            return false;
        }
        Image img;
        try {
            img = ImageIO.read(inputStream);
            return !(img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0);
        } catch (Exception e) {
            return false;
        }
    }
}
